<?php
/**
 * @copyright ©2020 北京麦盟科技
 * Created by PhpStorm.
 * User: jack_guo
 */

namespace app\plugins\community\controllers\api;


use app\core\response\ApiCode;
use app\plugins\community\forms\common\CommonMiddleman;

class ApiController extends \app\controllers\api\ApiController
{
    public function beforeAction($action)
    {
        //权限判断
        $permission = \Yii::$app->branch->childPermission(\Yii::$app->mall->user->adminInfo);
        if (!in_array('community', $permission)) {
            \Yii::$app->response->data = ['code' => ApiCode::CODE_ERROR, 'msg' => '无社区团购权限'];
            return false;
        }

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $this->bindMiddleman();
    }

    private function bindMiddleman()
    {
        if (\Yii::$app->user->isGuest) {
            return $this;
        }
        $headers = \Yii::$app->request->headers;
        $userId = empty($headers['x-user-id']) ? null : $headers['x-user-id'];
        if (!$userId) {
            return $this;
        }
        try {
            $common = CommonMiddleman::getCommon();
            $middleman = $common->getConfig($userId);
            $common->bindMiddleman($middleman, \Yii::$app->user->id);
        } catch (\Exception $exception) {
            \Yii::error($exception->getMessage());
        }
        return $this;
    }
}
